import { loginApi, getUserInfo, logoutApi } from "@/api/login";
import { setToken, getToken, delToken } from "@/utils/auth";

export default {
  namespaced: true,

  state() {
    return {
      token: getToken() || "", // 用户token
      info: null, // 用户信息
      menus: [], // 用户菜单信息集合
    };
  },

  getters: {
    authRoutes(state) {
      return state.menus.filter((item) => item.type === 1);
    },
  },

  mutations: {
    setToken(state, payload) {
      state.token = payload;
      // 写入本地存储
      setToken(payload);
    },

    setInfo(state, payload) {
      state.info = payload;
    },

    setMenus(state, payload) {
      state.menus = payload;
    },
    clear(state){
      state.token = "";
      state.info = null;
      state.menus = [];
      delToken();
    }
  },

  actions: {
    // 登录动作
    async login({ commit }, payload) {
      const result = await loginApi(payload);
      commit("setToken", result.token);
    },

    // 获取用户信息动作
    async getInfo({ commit }) {
      const result = await getUserInfo();
      // console.log("result", result);
      commit("setInfo", result.info);
      commit("setMenus", result.menus);

      return result.menus.filter((item)=>item.type===1)
    },

    //登出动作
    async logout({commit}){
      await logoutApi();
      commit("clear");``    
    }
  },
};
